package com.yekong.house.biz.service.impl;


import com.google.common.collect.Lists;
import com.yekong.house.common.model.User;
import com.yekong.house.biz.mapper.UserMapper;
import com.yekong.house.biz.service.UserService;
import com.yekong.house.common.utils.BeanHelper;
import com.yekong.house.common.utils.HashUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;


@Service
public class UserServiceImpl implements UserService {

    private final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    UserMapper userMapper;

    @Autowired
    private FileServiceImpl fileService;

    @Autowired
    private MailServiceImpl mailService;



    @Value("${file.prefix}")
    private String imagePrefix;

    @Override
    public List<User> getUsers() {
        return userMapper.selectUsers();
    }

    /**
     * 1.插入数据库，非激活；密码用md5加密；保存头像到本地
     * 2. 生成key，绑定 email
     * 3. 发送邮件给用户
     * @param account
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addAccount(User account) {
        // 加密数据库
        account.setPasswd(HashUtil.encryPassword(account.getPasswd()));
        // 获取头像路径
        List<String> imgList =  fileService.getImgPath(Lists.newArrayList(account.getAvatarFile()));
        if(!imgList.isEmpty()){
            account.setAvatar(imgList.get(0));
            logger.info("图片路径:"+account.getAvatar());
        }
        BeanHelper.setDefaultProp(account,User.class);
        BeanHelper.onInsert(account);
        account.setEnable(0);// 刚注册时用户处于未激活的状态
        logger.info("用户属性配置完毕！");
        logger.info(account.toString());
        userMapper.saveUser(account);
        logger.info("保存用户成功！");
        //异步操作
        mailService.registerNotify(account.getEmail());
        logger.info("发送邮件成功！");
        return true;
    }



    public boolean enable(String key){
        return mailService.enable(key);
    }

    /**
     * 1. 认证用户
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public User auth(String username, String password) {
        User user = new User();
        user.setEmail(username);
        user.setPasswd(HashUtil.encryPassword(password));
        user.setEnable(1);
        List<User> list = getUserByQuery(user);
        if(!list.isEmpty()){
            return list.get(0);
        }
        return null;
    }


    /**
     * 查询用户
     * @param user
     * @return
     */
    public List<User> getUserByQuery(User user){
        List<User> list = userMapper.selectUsersByQuery(user);
        list.forEach(u->{
            u.setAvatar(imagePrefix+u.getAvatar());
        });
        return list;
    }

    /**
     * 修改用户
     *
     * @param updateUser
     * @param email
     */
    @Override
    public void updateUser(User updateUser, String email) {
        BeanHelper.onUpdate(updateUser);
        userMapper.update(updateUser);
    }

    /**
     * 根据 id 查找用户
     *
     * @param id
     * @return
     */
    public User getUserById(Long id) {
        User queryUser = new User();
        queryUser.setId(id);
        List<User> users = getUserByQuery(queryUser);
        if (!users.isEmpty()) {
            return users.get(0);
        }
        return null;
    }


    public void resetNotify(String username) {
        mailService.resetNotify(username);
    }

    /**
     * 重置密码操作
     * @param
     * @param key
     */
    @Transactional(rollbackFor=Exception.class)
    public User reset(String key,String password){
        String email = getResetEmail(key);
        User updateUser = new User();
        updateUser.setEmail(email);
        updateUser.setPasswd(HashUtil.encryPassword(password));
        userMapper.update(updateUser);
        mailService.invalidateResetKey(key);
        return getUserByEmail(email);
    }
    public User getUserByEmail(String email) {
        User queryUser = new User();
        queryUser.setEmail(email);
        List<User> users = getUserByQuery(queryUser);
        if (!users.isEmpty()) {
            return users.get(0);
        }
        return null;
    }

    public String getResetEmail(String key) {
        String email = "";
        try {
            email =  mailService.getResetEmail(key);
        } catch (Exception ignore) {
        }
        return email;
    }

}
